<?php

namespace addons\tools\controller\api\v1;

use addons\tools\model\MealOrder as MealOrderModel;
use app\common\controller\Api;
use addons\tools\model\Meal as MealModel;
use EasyWeChat\Factory;
use Yansongda\Pay\Pay;

class Meal extends Api
{

    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $model = new MealModel();
        $list = $model->getLists();
        $this->success(__('获取数据成功'), $list);
    }

    /**
     * 详情
     * @return void
     */
    public function detail()
    {
        $mealId = $this->request->get('meal_id', 0);
        if (!$mealId)
            $this->error('参数错误');
        $model = new MealModel();
        $this->success('', $model->getDetail($mealId));
    }

    /**
     * 生成预支付订单
     * @return void
     */
    public function buy()
    {
        $params = $this->request->post();
        if (empty($params))
            $this->error('参数错误');
        if (empty($params['meal_id'])) {
            $this->error('参数错误');
        }
        $mealId = $params['meal_id'];
        $model = new MealModel();
        $detail = $model->getDetail($mealId);
        if (!$detail) {
            $this->error('套餐不存在');
        }
        $userId = $this->auth->id;
        $orderSn = create_order_sn();
        $data = [
            'user_id'    => $userId,
            'meal_id'    => $mealId,
            'order_sn'   => $orderSn,
            'price'      => $detail['price'],
            'days'       => $detail['days'],
            'type'       => $detail['type'],
            'pay_status' => 0
        ];
        $mealOrderModel = new MealOrderModel();
        if ($order = $mealOrderModel->getDetail(['user_id' => $userId, 'pay_status' => 0, 'meal_id' => $mealId])) {
            if ($order->save($data) === false)
                $this->error('支付失败');
        }
        if (!$mealOrderModel->save($data))
            $this->error('支付失败');

        $order = [
            'out_trade_no' => $orderSn,
            'description'  => $orderSn,
            'amount'       => [
                'total'    => (int)bcmul($detail->price, 100, 2),
                'currency' => 'CNY',
            ],
            'payer'        => [
                'openid' => $this->auth->third->openid,
            ],

        ];
        Pay::config(config('pay'));
        $result = Pay::wechat()->mini($order);
        if (!$result) {
            $this->error('支付失败');
        }
        $this->success('生成预支付订单成功', [
            'order_sn' => $mealOrderModel->order_sn,
            'pay_info' => $result
        ]);
    }

    /**
     * 支付
     * @return void
     */
    public function pay()
    {
        $orderSn = $this->request->post('order_sn', '');
        if (!$orderSn)
            $this->error('参数错误');
    }

}